<template>
  <div class="mine-box">
    <van-nav-bar title="个人设置" />

    <!--我的界面操作跳转显示列表-->
    <div class="mine-content">

      <img
        class="user-img"
        :src="userAvatar"
        @click="clickUploadImg"
      >

      <van-cell-group class="gap-s">
        <!-- <van-cell title="头像" is-link class="shadow" :value="nickname"/> -->
        <van-cell
          title="昵称"
          is-link
          class="shadow"
          :value="nickname"
          @click="clickChangeName"
        />
        <van-cell title="手机号" is-link class="shadow" :value="usermobile"/>
        <van-cell title="密码修改" is-link class="shadow" @click="clickSetting"/>
      </van-cell-group>

      <van-cell-group class="gap-s">
        <van-cell title="关于我们" is-link @click="clickAboutus" style="display:none"/>
        <van-cell title="生成二维码" v-if="islogin" is-link class="shadow" @click="geterweima"/>
      </van-cell-group>
      <div id="qrcode" @click="showImg"></div>
      <van-button size="large" @click="loginOut">退出登录</van-button>
    </div>

    <van-dialog
      v-model="showChangeName"
      show-cancel-button
      :before-close="beforeClose"
    >
      <van-field
        v-model="nickname"
        autofocus
        label="输入用户名："
      />
    </van-dialog>

    <van-dialog
      v-model="showImgChoose"
      show-cancel-button
      :before-close="beforeImgClose"
      style="width: 300px;"
    >
      <div class="img-container">
        <croppa
          v-model="myCroppa"
          :width="280"
          :height="280"
          placeholder="点击上传头像"
          placeholder-color="#777"
          :placeholder-font-size="14"
          :initial-image="userAvatar"
          :prevent-white-space="true"
        >
        </croppa>
      </div>
    </van-dialog>
  </div>
</template>

<script>
  import QRCode from 'qrcodejs2'
  import { ImagePreview } from 'vant';
  import { Toast } from 'vant';
  //图片裁剪的css
  import 'vue-croppa/dist/vue-croppa.css'

  export default {
    data(){
      return {
        showChangeName: false,
        showImgChoose: false,
        myCroppa: {},
        config: {
            value: 'https://www.baidu.com',
            imagePath: './examples/assets/logo.png',
            filter: 'color'
        },
        erweimaControl:true,
        islogin:false,
        downloadButton: false,
        //  用户账l号信息
        accountList: [],

        //用户号码
        hideNum:null,

        //  绑定微信授权flag
        bindIndex: false,

        bindTitle:'待绑定',
        // 用户头像
        userAvatar:'',
        //  版本参数
        param_uuid:null,

        param_scource:null,

        nickname:"",
        usermobile:"",
        imgsrc:"",
        userid:""
      }
    },
    created(){

    },
    mounted(){
      if(!sessionStorage.getItem("usermessage")) {
        this.$router.push('/login');
      }
      active_g = 5;
      var userMessage = JSON.parse(sessionStorage.getItem("usermessage"));
      if(userMessage){
      	this.userid = userMessage.user.id;
        this.islogin = true;
        this.usermobile = userMessage.user.mobile;
        token_g = userMessage.token;
        this.$axios({
            method: "PATCH",
            url: url_g + "/user/",
            headers: {
            'Authorization': 'Bearer ' + token_g
            }
          }).then((res) => {
            if(res && res.data){
              this.userAvatar = res.data.avatar;
              this.nickname = res.data.nick_name;
            }
          }).catch((e)=>{
            Toast('您输入的信息有误或网络有问题，请检查重试！');
        })
      }
    },
    methods:{
      showImg(){
        if(this.imgsrc){
          ImagePreview([
            this.imgsrc
          ]);
        }
      },
      clickChangeName() {
        this.showChangeName = true
      },
      beforeClose(action, done) {
        if (action === 'confirm') {
          this.$axios({
            method: "PATCH",
            url: url_g + "/user/",
            data: {
              nick_name: this.nickname
            },
            headers: {
              'Authorization': 'Bearer ' + token_g
            }
          }).then((res) => {
            if(res && res.data){
              this.nickname = res.data.nick_name
              done()
            }
          }).catch((e)=>{
            Toast('您输入的信息有误或网络有问题，请检查重试！');
          })
        } else {
          done();
        }
      },
      clickUploadImg() {
        this.showImgChoose = true
        this.myCroppa.refresh()
      },
      beforeImgClose(action, done) {
        if (action === 'confirm') {
          this.myCroppa.generateBlob((blob) => {
            if(!blob) {
              Toast('请选择图片!')
              done(false)
              return false
            }
            // write code to upload the cropped image file (a file is a blob)
            const formData = new FormData()
            formData.append('img_file', blob)
            this.$axios({
              method: "POST",
              url: url_g + "/user/avatar/",
              data: formData,
              headers: {
                'Authorization': 'Bearer ' + token_g
              }
            }).then((res) => {
              done()
              if(res && res.data){
                for(let key in res.data) {
                  if(key != 'code') {
                    this.userAvatar = res.data[key]
                    return false
                  }
                }
              }
            }).catch((e)=>{
              Toast('您输入的信息有误或网络有问题，请检查重试！');
            })
          }, 'image/jpeg', 0.8) // 80% compressed jpeg file
        } else {
          done();
        }
      },
      geterweima(){
        this.qrcode();
      },
      qrcode () {
        var $this = this;
        if(this.erweimaControl){
          let qrcode = new QRCode('qrcode', {
            width: 200,
            margin:"0 auto",
            height: 200, // 高度
            text: 'http://www.autoken.vip?userid='+$this.userid, // 二维码内容
            render: 'canvas', // 设置渲染方式（有两种方式 table和canvas，默认是canvas）
            background: '#f0f'
            // foreground: '#ff0'
          })
          this.erweimaControl = false;
          setTimeout(function(){
            let ele = document.getElementById("qrcode");
            $this.imgsrc = ele.children[1].getAttribute("src");
          },500)
        }

      },
      loginOut() {

         this.$axios({
            method: "POST",
            url: url_g + "/logout/",
            headers: {
            'Authorization': 'Bearer ' + token_g
            }
          }).then((res) => {
            this.$router.push('/login');
            sessionStorage.setItem("usermessage","")
          }).catch((e)=>{
            Toast('您输入的信息有误或网络有问题，请检查重试！');
          })
      },

      //  判断手机来源
      ismobile(test){
        var u = navigator.userAgent, app = navigator.appVersion;
        if(/AppleWebKit.*Mobile/i.test(navigator.userAgent) || (/MIDP|SymbianOS|NOKIA|SAMSUNG|LG|NEC|TCL|Alcatel|BIRD|DBTEL|Dopod|PHILIPS|HAIER|LENOVO|MOT-|Nokia|SonyEricsson|SIE-|Amoi|ZTE/.test(navigator.userAgent))){
          if(window.location.href.indexOf("?mobile")<0){
            try{
              if(/iPhone|mac|iPod|iPad/i.test(navigator.userAgent)){
                //document.getElementsByClassName("van-tabbar")[0].style = {};
                //document.getElementsByClassName("van-tabbar")[0].style.display = "none";
                return 1;
              }else{
                return 0;
              }
            }catch(e){
            }
          }
        }else if( u.indexOf('iPad') > -1){
          //document.getElementsByClassName("van-tabbar")[0].style = {};
          //document.getElementsByClassName("van-tabbar")[0].style.display = "none";
          return 0;

        }else{
          return 1;


        }
      },

      //  手机号码隐藏中间四位
      hideTel(param_tel){

        var telStr = param_tel.substr(0,3)+"****"+param_tel.substr(7);

        return telStr;
      },
      //  api接口拉取用户个人信息


      //获取界面url参数 name
      GetQueryString(name){
        var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
        var r = window.location.search.substr(1).match(reg);
        if(r!=null)return  unescape(r[2]); return null;
      },
      clickAboutus() {
        this.$router.push('/appupload');
      },
      clickSetting() {
        this.$router.push('/passwordreset');
      },
      //获取手机唯一标志符
      uuid() {
        var s = [];
        var hexDigits = "0123456789abcdef";
        for (var i = 0; i < 36; i++) {
          s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
        }
        s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
        s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
        s[8] = s[13] = s[18] = s[23] = "-";

        var uuid = s.join("");

        return uuid;
      },

    }
  }
</script>

<style scoped>
  #qrcode{
    width:200px;
    height:auto;
    margin:10px auto;
  }
  .mine-box{
    background: #f5f5f5;
    overflow: auto;
    height: 100vh;
  }
  .mine-content {
    padding-bottom: 60px;
    overflow: auto;
  }
  .van-button--large{
    border:none;
    margin-top:10px;
  }
  p{
    padding: 0;
    margin: 0;
  }

  .head-img{
    width: 60px;
    height: 60px;
    border-radius: 100%;
    display: block;
  }

  .mine-info{
    position: relative;
    padding: 0 12px 40px;
    background: #fff;
  }
  [class*=van-hairline]::after{
    border-color: #fff;
  }

  .info-content{
    position: absolute;
    top: 2px;
    left: 97px;
  }

  .icon-confirm{
    width: 16px;
    height: 16px;
    position: absolute;
    top: 0;
    left: 48px;
    padding: 1px 0;
  }

  p.confirm-title{
    font-size: 13px;
    line-height: 18px;
    color: #025596;
  }

  p.confirm-title-grey{
    font-size: 13px;
    line-height: 18px;
    color: #e5e5e5;
  }
  .confirm-content{
    position: relative;
    margin-top: 5px;
  }

  p.tel-num{
    font-size: 24px;
    line-height: 33px;
    color: #333333;
    font-weight: 500;
  }

  .gap-m{
    margin-top: 40px;
  }

  .gap-s{
    margin-top: 10px;
  }
  [class*=shadow]::after{
    border-color: #e5e5e5;
  }
  .user-img {
    display: block;
    width: 100px;
    height: 100px;
    margin: 10px auto;
    border-radius: 50%;
  }
  .img-container {
    padding: 10px;
  }
</style>
